package cn.wolfcode.trip.base.service.impl;

import cn.wolfcode.trip.base.domain.Hotel;
import cn.wolfcode.trip.base.domain.HotelForm;
import cn.wolfcode.trip.base.domain.User;
import cn.wolfcode.trip.base.mapper.HotelFormMapper;
import cn.wolfcode.trip.base.mapper.HotelMapper;
import cn.wolfcode.trip.base.mapper.UserMapper;
import cn.wolfcode.trip.base.service.IHotelFormService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.List;

@Service
public class HotelFormServiceImpl implements IHotelFormService {
    @Autowired
    private HotelFormMapper formMapper;
    @Autowired
    private HotelMapper hotelMapper;
    @Autowired
    private UserMapper userMapper;

    public void save(HotelForm hotelForm, User user) {
        int days = (int) ((hotelForm.getEndDate().getTime() - hotelForm.getBeginDate().getTime()) / (1000*3600*24));
        Hotel hotel = hotelMapper.selectByPrimaryKey(hotelForm.getHotel().getId());
        BigDecimal totalPrice = hotel.getPrice().multiply(new BigDecimal(days)).multiply(new BigDecimal(hotelForm.getRoomNumber()));
        hotelForm.setTotalPrice(totalPrice);
        if (totalPrice.compareTo(user.getBalance()) == 1){
            throw new RuntimeException("余额不足");
        }
        user.setBalance(user.getBalance().subtract(totalPrice));
        userMapper.updateBalance(user);
        formMapper.insert(hotelForm);
    }

    public List<HotelForm> getHotelForm(Long userId) {
        return formMapper.getHotelFormByUserId(userId);
    }
}
